import {
  config
} from '../utils/config.js';
import { BaseModel } from './base.js';

class Token {
  constructor() {
    this.tokenUrl = config.api_base_url + 'wechat/login';
  }
  login() {
    var token = wx.getStorageSync('token');
    if (!token) {
      this.getTokenFromServer();
    }
  }
  getTokenFromServer(callBack) {
    var that = this;
    wx.login({
      success: function (res) {
        that.login(res.code)
      }
    })
  }

  login(code) {
    let that = this
    wx.request({
      url: that.tokenUrl + '?jsCode=' + code,
      method: 'POST',
      header: {
        'Content-type': 'application/json'
      },
      data: {
        jsCode: code
      },
      success: function (res) {
        console.log(res)
        if (res.data.success || res.data.code == 200) {
          wx.setStorageSync('token', res.data.data.token);
          let base = new BaseModel()
          base.validateBindMobile().then(res => {
            console.log("this method validate bind mobile")
            console.log(res)
            if (!res.data) {
              wx.navigateTo({
                url: '/pages/login/index',
              })
            }
          })
          // 校验当前用户是否绑定手机号码

        
          if (res.data.data.userInfo && !res.data.data.userInfo.mobile) {
           
          }
        } else {
          wx.setStorageSync('token', '1');
          wx.showModal({
            title: '友情提示',
            content: res.data.errorMsg
          })
        }
      },
      fail(error) {
        wx.showModal({
          title: '请求服务提示',
          content: '请求的服务无法访问、网络错误（打开调试模式）',
          success(res) {
            if (res.confirm) {

            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        wx.setStorageSync('token', '1');
        console.log("66666")
        reject(error.data)
      }
    })
  }
}
export {
  Token
}